// UUID中允许出现的基本字符;
const baseChar: string[] = (() => {
    const array: string[] = [];
    // 将数字0-9加入到 baseChar 中
    for (let i = 0; i < 10; i++) {
        array.push(i.toString(10));
    }
    // 将小写字母a-z加入到 baseChar 中
    for (let i = 0; i < 26; i++) {
        array.push(String.fromCharCode('a'.charCodeAt(0) + i));
    }
    // 将大写字母A-Z加入到 baseChar 中
    for (let i = 0; i < 26; i++) {
        array.push(String.fromCharCode('A'.charCodeAt(0) + i));
    }
    return array;
})();

// 进制转换/数字转字符
function scaleTransition(value: number, base = baseChar): string {
    if (value < 0) {
        throw new Error('scaleTransition Error, value < 0');
    }
    if (value === 0) {
        return base[0];
    }
    const radix = base.length;
    let result = '';
    let resValue = value;
    while (resValue > 0) {
        result = base[resValue % radix] + result;
        resValue = Math.floor(resValue / radix);
    }
    return result;
}

// UUID参数集合, 使用 count 能保证在本地环境中UUID绝对不会重复.
const UuidObject: Record<string, { prefix: string; count: number }> = {};
// 生成随机的UUID
export default function createUUID(prefix = '') {
    let uuidObject = UuidObject[prefix];
    if (uuidObject === undefined) {
        const str = `${scaleTransition(Date.now())}-${scaleTransition(
            Math.floor(Math.random() * 10000000000),
        )}-`;
        if (prefix) {
            uuidObject = {
                prefix: `${prefix}-${str}`,
                count: 0,
            };
        } else {
            uuidObject = {
                prefix: str,
                count: 0,
            };
        }
        UuidObject[prefix] = uuidObject;
    }
    return uuidObject.prefix + scaleTransition(uuidObject.count++);
}

